Page({
  data: {
    members: [],
    selectedMemberId: null,
    selectedMemberName: '',
    recordTypes: [
      { id: 'bloodPressure', name: '血压', unit: 'mmHg', format: '收缩压/舒张压', placeholder: '例如：120/80' },
      { id: 'bloodSugar', name: '血糖', unit: 'mmol/L', format: '数值', placeholder: '例如：5.6' },
      { id: 'weight', name: '体重', unit: 'kg', format: '数值', placeholder: '例如：65' },
      { id: 'height', name: '身高', unit: 'cm', format: '数值', placeholder: '例如：170' },
      { id: 'temperature', name: '体温', unit: '°C', format: '数值', placeholder: '例如：36.5' },
      { id: 'heartRate', name: '心率', unit: 'bpm', format: '数值', placeholder: '例如：75' },
      { id: 'sleep', name: '睡眠', unit: '小时', format: '数值', placeholder: '例如：7.5' }
    ],
    selectedTypeId: 'bloodPressure',
    selectedTypeName: '血压',
    selectedTypeUnit: 'mmHg',
    selectedTypeFormat: '收缩压/舒张压',
    selectedTypePlaceholder: '例如：120/80',
    recordValue: '',
    systolic: '', // 收缩压
    diastolic: '', // 舒张压
    date: '',
    time: '',
    note: '',
    isSubmitting: false
  },

  onLoad: function (options) {
    // 设置当前日期和时间
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const hour = now.getHours().toString().padStart(2, '0')
    const minute = now.getMinutes().toString().padStart(2, '0')
    
    this.setData({
      date: `${year}-${month}-${day}`,
      time: `${hour}:${minute}`
    })

    // 加载家庭成员
    this.loadMembers()

    // 如果传入了成员ID，则预选该成员
    if (options.memberId) {
      this.selectMember(options.memberId)
    }
  },

  loadMembers: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从服务器获取家庭成员数据
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const members = res.data.data.members || [];
          this.setData({
            members: members
          });
          
          // 如果有预选的成员ID，确保它存在于加载的成员列表中
          if (this.data.selectedMemberId) {
            const selectedMember = members.find(m => m.id === this.data.selectedMemberId);
            if (!selectedMember && members.length > 0) {
              this.selectMember(members[0].id);
            }
          }
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  selectMember: function (id) {
    // 确保ID是数字类型
    const memberId = typeof id === 'string' ? parseInt(id) : id;
    
    // 查找对应成员
    const member = this.data.members.find(m => m.id === memberId);
    
    if (member) {
      this.setData({
        selectedMemberId: memberId,
        selectedMemberName: member.name
      });
    } else {
      console.warn('未找到ID为', memberId, '的成员');
    }
  },

  onMemberChange: function (e) {
    const index = e.detail.value
    const member = this.data.members[index]
    
    if (member) {
      this.setData({
        selectedMemberId: member.id,
        selectedMemberName: member.name
      })
    }
  },

  onTypeChange: function (e) {
    const index = e.detail.value
    const type = this.data.recordTypes[index]
    
    this.setData({
      selectedTypeId: type.id,
      selectedTypeName: type.name,
      selectedTypeUnit: type.unit,
      selectedTypeFormat: type.format,
      selectedTypePlaceholder: type.placeholder,
      recordValue: '', // 清空值，因为类型改变了
      systolic: '',
      diastolic: ''
    })
  },

  onDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  onTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },

  onValueInput: function (e) {
    this.setData({
      recordValue: e.detail.value
    })
  },

  // 收缩压输入处理
  onSystolicInput: function (e) {
    this.setData({
      systolic: e.detail.value
    })
  },

  // 舒张压输入处理
  onDiastolicInput: function (e) {
    this.setData({
      diastolic: e.detail.value
    })
  },

  onNoteInput: function (e) {
    this.setData({
      note: e.detail.value
    })
  },

  submitRecord: function () {
    // 表单验证
    if (!this.data.selectedMemberId) {
      wx.showToast({
        title: '请选择家庭成员',
        icon: 'none'
      })
      return
    }

    // 血压特殊处理
    if (this.data.selectedTypeId === 'bloodPressure') {
      if (!this.data.systolic || !this.data.diastolic) {
        wx.showToast({
          title: '请输入完整的血压值',
          icon: 'none'
        })
        return
      }
      // 组合血压值
      this.setData({
        recordValue: `${this.data.systolic}/${this.data.diastolic}`
      })
    } else if (!this.data.recordValue) {
      wx.showToast({
        title: '请输入记录值',
        icon: 'none'
      })
      return
    }

    // 防止重复提交
    if (this.data.isSubmitting) {
      return
    }

    this.setData({
      isSubmitting: true
    })

    // 构建记录数据
    const recordData = {
      member_id: this.data.selectedMemberId,
      type: this.data.selectedTypeName,
      type_id: this.data.selectedTypeId,
      value: this.data.recordValue,
      unit: this.data.selectedTypeUnit,
      record_time: `${this.data.date} ${this.data.time}`,
      note: this.data.note
    }

    // 血压额外添加收缩压和舒张压单独的值
    if (this.data.selectedTypeId === 'bloodPressure') {
      recordData.systolic = parseInt(this.data.systolic);
      recordData.diastolic = parseInt(this.data.diastolic);
    }

    console.log('准备发送的记录数据:', recordData);
    
    // 获取token
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '登录状态失效，请重新登录',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      return;
    }

    // 发送真实API请求添加记录
    wx.request({
      url: 'http://localhost:3000/api/records',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: recordData,
      success: (res) => {
        console.log('服务器响应:', res.data);
        if (res.data.success) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            // 返回并刷新上一页
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2]; // 获取上一个页面
            
            // 如果上一页是记录页面，触发刷新
            if (prevPage && prevPage.route === 'pages/records/records') {
              prevPage.loadRecords();
            }
            
            wx.navigateBack();
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.message || '添加失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({
          isSubmitting: false
        });
      }
    });
  },

  cancel: function () {
    wx.navigateBack()
  }
}) 